<template>
    <div style="width: 100%">
        <h1>通知管理</h1>

        <el-dialog title="添加通知"  :visible.sync="dialogFormVisible">
            <el-form :model="form" :rules="rules"  ref="form">

                <el-row>
                    <el-col :span="20" :offset="2">
                        <el-form-item label="标题:" label-width="90" prop="title">
                            <el-input v-model="form.title" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20" :offset="2">
                        <el-form-item label="通知内容:" label-width="90" prop="content">
                            <el-input
                                    type="textarea"
                                    :rows="5"
                                    placeholder="请输入内容"
                                    v-model="form.content"
                            >
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="10" :offset="2">
                        <el-form-item label="通知的等级：" prop="levelId">
                            <el-select v-model="form.levelId"  placeholder="请选择等级">
                                <el-option
                                        v-for="item in noticeLevelList"
                                        :key="item.id"
                                        :label="item.levelName"
                                        :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="10" :offset="2">
                        <el-form-item label="通知的类型：" prop="typeId">
                            <el-select v-model="form.typeId" placeholder="请选择类型">
                                <el-option
                                        v-for="item in noticeTypeList"
                                        :key="item.id"
                                        :label="item.typeName"
                                        :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row v-show="show">
                    <el-col :span="10" :offset="2">
                        <el-form-item label="通知的教师或学生（可多选）：" prop="classesAndStudent">

                            <el-cascader
                                    v-model="form.classesAndStudent"
                                    :show-all-levels="false"
                                    placeholder="请选择"
                                    filterable
                                    clearable
                                    :options="prop"
                                    :props="props"
                                    @change="handleClassOrStudentChange"
                            >
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row v-show="!show">
                    <el-col :span="10" :offset="2">
                        <el-form-item label="通知的教师或学生：">
                            <el-button @click="handleLookPeople(form.id)">点击查看</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-row>
                    <el-col :span="8" :offset="2">
                        <el-form-item label="是否发布：" prop="publish">
                            <el-switch
                                    v-model="form.publish"
                                    >
                            </el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleReset">重置</el-button>
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handlerAddStudent">提交</el-button>
            </div>

        </el-dialog>




        <!--查看通知人员-->
        <el-dialog title="通知人员表" :visible.sync="lookPeople">

            <el-tabs v-model="activeName" >

                <el-tab-pane label="学生" name="first">
                    <el-table
                            :data="noticeStudentList"
                            border
                            style="width: 100%">
                        <el-table-column
                                fixed
                                prop="id"
                                label="id"
                                width="200"
                        >
                        </el-table-column>
                        <el-table-column
                                prop="name"
                                label="姓名"
                                width="200">
                        </el-table-column>
                        <el-table-column
                                fixed="right"
                                label="操作"
                                width="300">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="handleDelStudent(scope.$index,scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!--        分页-->
                    <el-pagination
                            background
                            layout="prev, pager, next"
                            :current-page="noticeStudentPageNum"
                            :page-size="noticeStudentPageInfo.pageSize"
                            :total="noticeStudentPageInfo.total"
                            :hide-on-single-page="true"
                            @current-change="handleNoticeStudent"
                    >
                    </el-pagination>
                </el-tab-pane>

                <el-tab-pane label="老师" name="second">
                    <el-table
                            :data="noticeTeacherList"
                            border
                            style="width: 100%">
                        <el-table-column
                                fixed
                                prop="id"
                                label="id"
                                width="200"
                        >
                        </el-table-column>

                        <el-table-column
                                prop="name"
                                label="姓名"
                                width="200">
                        </el-table-column>
                        <el-table-column
                                fixed="right"
                                label="操作"
                                width="300">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="handleDelTeacher(scope.$index,scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!--        分页-->
                    <el-pagination
                            background
                            layout="prev, pager, next"
                            :current-page="noticeTeacherPageNum"
                            :page-size="noticeTeacherPageInfo.pageSize"
                            :total="noticeTeacherPageInfo.total"
                            :hide-on-single-page="true"
                            @current-change="handleNoticeTeacher"
                    >
                    </el-pagination>
                </el-tab-pane>


            </el-tabs>

            <span slot="footer" class="dialog-footer">
                <el-button @click="lookPeople = false">取 消</el-button>
                <el-button type="primary" @click="lookPeople = false">确 定</el-button>
            </span>
        </el-dialog>




        <!--通知查询-->
        <el-row :gutter="20">
            <el-col :span="3"><el-button type="primary" @click="handlerAddEstimate">添加</el-button></el-col>
            <el-col :span="1"  ><el-button type="danger" icon="el-icon-delete" @click="handleMultipleDelete">批量删除</el-button></el-col>

            <el-col :span="3" :offset="8">

                <el-select v-model="student.sex"  placeholder="请选择性别">
                    <el-option label="全部" value="全部"></el-option>
                    <el-option label="男" value="男"></el-option>
                    <el-option label="女" value="女"></el-option>
                </el-select>

            </el-col>

<!--            <el-col :span="3">-->
<!--                <el-select v-model="student.classesId"  filterable clearable placeholder="请选择班级">-->
<!--                    <el-option-->
<!--                            v-for="item in classesList"-->
<!--                            :key="item.id"-->
<!--                            :label="item.classesName"-->
<!--                            :value="item.id"-->
<!--                    >-->
<!--                    </el-option>-->
<!--                </el-select>-->
<!--            </el-col>-->


            <el-col :span="3">
                <el-input
                        placeholder="请输入姓名"
                        v-model="student.name"
                        clearable
                >
                </el-input>
            </el-col>

            <el-col :span="1"><el-button type="primary" plain @click="handleStudentList">搜索</el-button></el-col>
        </el-row>



        <!--通知列表-->
        <el-table
                v-loading="loading"
                ref="multipleTable"
                :data="pageInfo.list"
                tooltip-effect="dark"
                style="width: 90%;margin: 0 auto"
                @selection-change="handleSelectionChange">

            <el-table-column
                    type="selection"
                    min-width="5%">
            </el-table-column>

            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-form label-position="left" inline class="demo-table-expand">


                        <el-row :gutter="20">
                            <el-col :span="6" :offset="1">

                                <el-form-item label="通知标题">
                                    <span>{{ props.row.title }}</span>
                                </el-form-item>

                                <el-form-item label="通知类型">
                                    <span>{{ props.row.noticeType.typeName}}</span>
                                </el-form-item>

                                <el-form-item label="通知等级">
                                    <span>{{ props.row.noticeLevel.levelName}}</span>
                                </el-form-item>

                                <el-form-item label="录入人">
                                    <span>{{ props.row.inputTeacher.name}}</span>
                                </el-form-item>

                                <el-form-item label="通知人数">
                                    <span>{{ props.row.noticeNumber}}</span>
                                </el-form-item>

                            </el-col>

                            <el-col :span="6">

                                <el-form-item label="通知内容">
                                    <span>{{ props.row.content}}</span>
                                </el-form-item>

                            </el-col>
                        </el-row>

                    </el-form>
                </template>
            </el-table-column>

            <el-table-column
                    label="标题"
                    prop="title"
                    min-width="5%"
            >

            </el-table-column>

            <el-table-column
                    prop="content"
                    label="内容"
                    min-width="5%">
            </el-table-column>
<!--            <el-table-column-->
<!--                    prop="personal"-->
<!--                    label="是否为个人通知"-->
<!--                    min-width="5%"-->
<!--            >-->
<!--            </el-table-column>-->
            <el-table-column
                    prop="inputTeacher.name"
                    label="录入人"
                    min-width="5%"
            >
            </el-table-column>
            <el-table-column
                    label="录入时间"
                    sortable
                    min-width="5%"
            >
                <template slot-scope="scope">
                    <span>{{scope.row.inputTime.toLocaleString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')}}</span>
                </template>
            </el-table-column>


            <el-table-column
                    label="操作"
                    min-width="5%"
            >
                <template slot-scope="scope">

                    <el-tooltip content="编辑" placement="top">
                        <el-button
                                type="primary"
                                size="mini"
                                icon="el-icon-edit"
                                @click="handlerChange(scope.$index,scope.row)"
                        >编辑</el-button>
                    </el-tooltip>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--        分页-->
        <el-pagination
                background
                layout="prev, pager, next"
                :current-page="pageNum"
                :page-size="pageInfo.pageSize"
                :total="pageInfo.total"
                :hide-on-single-page="true"
                @current-change="handleStudentList"
        >
        </el-pagination>

    </div>

</template>

<script>
    let id = 0;


    export default {
        data() {
            let studentOrClassesSelector = (rule,value,callback) => {
                if(!value){
                    if(!this.show){
                        callback();
                    }
                    callback(new Error('学生或班级至少选择一个'));
                }else {
                    callback();
                }
            };



            return {
                form: {
                    typeId:1,
                    levelId:1,
                    publish:false,
                    title: '',
                    content:''
                },
                rules:{
                    title:[
                        { required: true, message: '请输入标题', trigger: 'blur' },
                    ],
                    content:[
                        { required:true, message: '请输入内容', trigger: 'blur' }
                    ],
                    classesAndStudent: [
                        { required: true, validator: studentOrClassesSelector, trigger: 'blur'},
                        { type: 'array', message: '请选择'}
                    ]
                },
                pageNum:1,
                student: {sex:"全部"},
                pageInfo: [],
                studentList: [],
                multipleSelection: [],
                input:'',
                noticeLevelList: [],
                noticeTypeList:[],
                dialogFormVisible : false,
                loading: true,
                show: true,

                //查看人员弹窗
                lookPeople:false,
                //人员列表
                noticeTeacherList:[],
                noticeStudentList:[],
                activeName:'first',
                noticeTeacherPageInfo:{},
                noticeStudentPageInfo:{},

                noticeTeacherPageNum:1,
                noticeStudentPageNum:1,
                lookNoticeId:'',

                delTeacherList:[],
                delStudentList:[],



                //学生或班级选择
                props: {
                    // emitPath:false,//返回值只有value
                    multiple: true,
                    lazy: true,
                    lazyLoad: this.handleGetClassOrStudent,
                },
                prop:[
                    {
                        value: 'all',
                        label: '全部',
                        leaf: true,
                        type: 'root',
                        disabled: false
                    },
                    {
                        value: 'allStudent',
                        label: '全部学生',
                        leaf: true,
                        type: 'root',
                        disabled: false
                    },
                    {
                        value: 'allTeacher',
                        label: '全部教师',
                        leaf: true,
                        type: 'root',
                        disabled: false
                    },
                    // {
                    //     value: 'class',
                    //     label: '班级(包含教师和学生)',
                    //     leaf: false,
                    //     type: 'root',
                    //     disabled: false
                    // },
                    {
                        value: 'student',
                        label: '学生',
                        leaf: false,
                        type: 'root',
                        disabled: false
                    },
                    {
                        value: 'teacher',
                        label: '教师',
                        leaf: false,
                        type: 'root',
                        disabled: false
                    }
                ]
            }

        },
        created() {
            this.handleStudentList()

        },
        methods: {
            //列表 条件查询
            handleStudentList(pageNum) {
                this.loading = true;
                if (typeof pageNum == "number") {
                    this.pageNum = pageNum;
                } else {
                    this.pageNum = 1;
                }

                // console.log(this.student)
                this.$axios.post("/manage/notice/list",{},{params:{pageNum:this.pageNum}}).then(response => {
                    console.log(response)
                    this.pageInfo = response.data.noticeList;
                    this.noticeLevelList = response.data.noticeLevelList;
                    this.noticeTypeList = response.data.noticeTypeList;
                    this.loading = false;
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //重置
            handleReset() {
                this.form = {
                    typeId:1,
                    levelId:1,
                    publish:false
                };
            },
            //添加如果存在修改的id清空
            handlerAddEstimate(){
                this.show = true;
                if(this.form.id!=null){
                    this.form = {
                        typeId:1,
                        levelId:1,
                        publish:false
                    };
                }
                this.dialogFormVisible = true;
            },
            //提交
            handlerAddStudent() {

                this.$refs["form"].validate(valid => {
                    if (valid) {
                        console.log(this.show)
                        if(this.show){
                            this.dialogFormVisible = false;
                            console.log(this.form)
                            let students=[];
                            let teachers=[];
                            let allStudent='';
                            let allTeacher = '';
                            let all = '';

                            this.form.classesAndStudent.forEach(item => {
                                if(item[0]==="student"){
                                    students.push(item[item.length-1]);
                                }
                                else if(item[0]==="teacher"){
                                    teachers.push(item[item.length-1]);
                                }
                                else if(item[0]==="allStudent"){
                                    allStudent='allStudent';
                                }
                                else if (item[0]==="allTeacher"){
                                    allTeacher = 'allTeacher';
                                }
                                else if(item[0]==="all"){
                                    all = 'all';
                                }

                            })
                            let notice = this.form;
                            let data = {students,teachers,allStudent,allTeacher,all,notice}
                            // let data={classes:[1,2,3],students:[4,5,6]}
                            console.log(data)
                            this.$axios.post("/manage/notice/save",data).then(response => {
                                if (response.code != 10001) {
                                    // this.handleStudentList();
                                    this.form = {
                                        typeId:1,
                                        levelId:1,
                                        publish:false
                                    };
                                }
                                this.dialogFormVisible = false;
                                this.handleStudentList(this.pageNum);
                            })
                        }
                        else {
                            this.$axios.post("/manage/notice/updataById",this.form).then(response => {

                                if (response.code != 10001) {
                                    // this.handleStudentList();
                                    this.form = {
                                        typeId:1,
                                        levelId:1,
                                        publish:false
                                    };
                                }
                                this.dialogFormVisible = false;
                                this.handleStudentList(this.pageNum);
                            })
                        }
                    }

                });
            },
            //修改
            handlerChange(index, row) {
                this.show = false;
                this.$axios.get("/manage/notice/findById/" + row.id).then(response => {
                    this.form = response.data.data;
                    this.dialogFormVisible = true;
                })

            },
            //单个删除
            handleDelete(row){
                this.$confirm('确认删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.get("/manage/notice/delete",{params:{id:row.id}}).then(response=>{
                        console.log(123)
                        this.handleStudentList();
                    })
                    console.log(456)
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //    批量删除
            handleMultipleDelete(){
                this.$confirm('确认删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var idList = [];
                    for (var i=0;i < this.multipleSelection.length;i++ ){
                        idList.push(this.multipleSelection[i].id);
                    }
                    this.$axios.post("/student/multipleDelete",idList).then(response=>{
                        if(response.data.code==10001){
                            return;
                        }
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        //刷新
                        this.handleStudentList();
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },



            //联级选择器获得学生或者班级或者教师
            handleGetClassOrStudent(node, resolve){
                // console.log(node);

                // console.log(level)
                const { data } = node;//第一次调用时node中什么也没有
                const { parent } = node;
                // console.log(node)
                if(data.type==="root"&&data.value!="teacher"){
                    //获得班级类型
                    this.$axios.get("/manage/classesType/list").then(response => {
                        // console.log(response.data.data)
                        const nodes = Array.from(response.data.data,item => ({
                            value: item.id,
                            label: item.typeName,
                            leaf: false,
                            type: 'classesType'
                        }))
                        //将nodes返回
                        resolve(nodes);
                    })
                }
                else if(data.value==="teacher"){
                    //获得教师
                    this.$axios.get("/manage/notice/findByTeacher").then(response => {
                        const nodes = Array.from(response.data.teacherList, item => (console.log(response),{
                            value: item.id,
                            label: item.name,
                            leaf: true,
                            type: 'teacher'
                        }))
                        resolve(nodes)
                    })
                }
                else if(data.type==='classesType'){
                    //获得班级
                    this.$axios.get("/manage/notice/noticeFindList/"+data.value).then(response => {
                        const nodes = Array.from(response.data.classesList,item => ({
                            value: item.id,
                            label: item.classesName,
                            leaf: parent.data.value!='student',
                            type: 'classes'
                        }))
                        resolve(nodes);
                    })
                }
                else if(data.type==='classes'&&parent.parent.value==='student'){
                    //获得学生
                    this.$axios.get("/manage/notice/findByClassStudent/"+data.value).then(response => {
                        const  nodes = Array.from(response.data.studentList,item => ({
                            value: item.id,
                            label: item.name,
                            leaf: true,
                            type: 'studnet'
                        }))
                        resolve(nodes)
                    })
                }
                resolve();
            },

        //选择器选择后触发
            handleClassOrStudentChange(node, resolve){
                // console.log(node)
                // console.log(node[0][0]=='allStudent')
                // console.log(node)
                // console.log(this.prop)

                if(node){
                    let allTeacher = false;//选择全部教师true
                    let allStudent = false;//选择全部学生true
                    let all = false;//选择全部 true
                    if(node.length>=1){

                        Array.from(node,(choose) => {//遍历node集合
                            if(choose[0]==="all"){
                                all = true;
                                this.form.classesAndStudent = [["all"]]//清空之前的选择
                                Array.from(this.prop,(item) => {
                                        if(item.value!="all"){
                                            item.disabled=true;//禁用其他选项
                                        }
                                    })
                            }
                            else if(!all){//选择不为全部时
                                Array.from(this.prop,(item) => {
                                    if(choose[0]==="allStudent"){//选择全部学生
                                        if(item.value==="student"){
                                            allStudent = true;
                                            item.disabled=true;
                                        }
                                    }
                                    if(choose[0]==="allTeacher"){//选择全部老师
                                        if(item.value==="teacher"){
                                            allTeacher = true;
                                            item.disabled=true;
                                        }
                                    }
                                })
                            }
                        })
                        if(!all){
                            Array.from(this.prop,(item) => {
                                if(!allStudent){
                                    if(item.value==="student"){
                                        item.disabled=false;
                                    }
                                }
                                if(!allTeacher){
                                    if(item.value==="teacher"){
                                        item.disabled=false;
                                    }
                                }
                            })
                        }

                    }
                    else {
                        Array.from(this.prop,(item) => {
                            item.disabled=false;//取消全部选择后 解除禁用
                        })
                    }
                }
            },

            //通知人员查看
            handleLookPeople(id){
                this.lookPeople = true;
                this.lookNoticeId = id;

                this.$axios.get("/manage/notice/findIdByStudent?id="+id).then( res => {
                    this.noticeStudentList=res.data.data.list;
                    this.noticeStudentPageInfo=res.data.data;
                    console.log(res)
                })

                this.$axios.get("/manage/notice/findIdByTeacher?id="+id).then( res => {
                    this.noticeTeacherList=res.data.data.list;
                    this.noticeTeacherPageInfo=res.data.data;
                    console.log(res)
                })

            },
            //获得通知学生
            handleNoticeStudent(noticeStudentPageNum){
                let id = this.lookNoticeId;
                if (typeof noticeStudentPageNum == "number") {
                    this.noticeStudentPageNum = noticeStudentPageNum;
                } else {
                    this.noticeStudentPageNum = 1;
                }
                this.$axios.get("/manage/notice/findIdByStudent?id="+id+"&pageNum="+noticeStudentPageNum).then( res => {
                    this.noticeStudentList=res.data.data.list;
                    this.noticeStudentPageInfo=res.data.data;
                    // console.log(res)
                })
            },
            //获得通知教师
            handleNoticeTeacher(noticeTeacherPageNum){
                let id = this.lookNoticeId;
                if (typeof noticeTeacherPageNum == "number") {
                    this.noticeTeacherPageNum = noticeTeacherPageNum;
                } else {
                    this.noticeTeacherPageNum = 1;
                }
                this.$axios.get("/manage/notice/findIdByTeacher?id="+id+"&pageNum="+noticeTeacherPageNum).then( res => {
                    this.noticeTeacherList=res.data.data.list;
                    this.noticeTeacherPageInfo=res.data.data;
                    // console.log(res)
                })
            },
            //删除通知学生
            handleDelStudent(index,row){
                console.log(this.lookNoticeId)
                let notice = {
                    noticeId:this.lookNoticeId,
                    studentId:row.id
                }

                this.$confirm('是否要删除此人的通知?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // this.delStudentList.push(notice)

                    this.$axios.post("/manage/notice/delNoticeStudent",notice).then(res => {
                        if(res.data.code==200){
                            this.handleNoticeStudent(this.noticeStudentPageNum);
                        }
                    })
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
                console.log(notice)
                console.log(index)
            },
            //删除通知教师
            handleDelTeacher(index,row){
                console.log(this.lookNoticeId)
                let notice = {
                    noticeId:this.lookNoticeId,
                    teacherId:row.id
                }

                this.$confirm('是否要删除此人的通知?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.delStudentList.push(notice)

                    this.$axios.post("/manage/notice/delNoticetTeacher",notice).then(res => {
                        if(res.data.code==200){
                            this.handleNoticeTeacher(this.noticeTeacherPageNum);
                        }
                    })

                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
                // this.delTeacherList.push(notice)
            }


        }
    }
</script>

<style>
    body{
        text-align: center;
    }

    .demo-table-expand {
        font-size: 0;
    }
    .demo-table-expand  label{
        width: 90px;
        color: #99a9bf;
    }

    .demo-table-expand .el-form-item {
        margin-left: 10%;
        margin-bottom: 0;
        width: 50%;
        display: block;
    }

</style>